<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Phase 7: 范围发布通知测试页面 - 智能通知系统</title>
    
    <!-- 安全头配置 -->
    <meta http-equiv="Content-Security-Policy" content="
        default-src 'self'; 
        script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; 
        style-src 'self' 'unsafe-inline'; 
        img-src 'self' data: https:; 
        font-src 'self' https:; 
        connect-src 'self' http://localhost:48081 http://localhost:48082; 
        frame-src 'none'; 
        object-src 'none';
        base-uri 'self';
        form-action 'self';">
    <meta http-equiv="X-Content-Type-Options" content="nosniff">
    <meta http-equiv="X-Frame-Options" content="DENY">
    <meta http-equiv="X-XSS-Protection" content="1; mode=block">
    <meta http-equiv="Referrer-Policy" content="strict-origin-when-cross-origin">
    
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: #333;
        }

        .container {
            max-width: 1600px;
            margin: 0 auto;
            padding: 20px;
        }

        .header {
            text-align: center;
            color: white;
            margin-bottom: 30px;
        }

        .header h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
        }

        .header .subtitle {
            font-size: 1.2rem;
            opacity: 0.9;
            margin-bottom: 20px;
        }

        .feature-highlight {
            background: rgba(255, 193, 7, 0.15);
            border: 2px solid #ffc107;
            border-radius: 15px;
            padding: 20px;
            margin: 20px auto;
            max-width: 900px;
            backdrop-filter: blur(10px);
            box-shadow: 0 10px 30px rgba(255, 193, 7, 0.2);
        }

        .feature-highlight h3 {
            color: #ffc107;
            font-size: 1.3rem;
            margin-bottom: 15px;
            text-align: center;
            text-shadow: 1px 1px 2px rgba(0,0,0,0.5);
        }

        .feature-list {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
            color: white;
            font-size: 0.95rem;
        }

        .feature-item {
            background: rgba(255, 255, 255, 0.1);
            padding: 12px;
            border-radius: 8px;
            border-left: 4px solid #ffc107;
        }

        /* 阶段导航 */
        .phase-navigation {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 15px;
            margin: 20px 0;
            flex-wrap: wrap;
        }

        .phase-nav-item {
            background: rgba(255, 255, 255, 0.15);
            color: white;
            padding: 8px 15px;
            border-radius: 25px;
            text-decoration: none;
            font-size: 0.9rem;
            transition: all 0.3s ease;
            border: 1px solid rgba(255, 255, 255, 0.3);
        }

        .phase-nav-item:hover {
            background: rgba(255, 255, 255, 0.25);
            transform: translateY(-2px);
        }

        .phase-nav-item.current {
            background: #ffc107;
            color: #333;
            font-weight: bold;
        }

        /* 认证区域 */
        .auth-section {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 30px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        }

        .auth-controls {
            display: grid;
            grid-template-columns: 1fr auto auto;
            gap: 15px;
            align-items: center;
            margin-bottom: 20px;
        }

        .role-selector {
            padding: 12px;
            border: 2px solid #ddd;
            border-radius: 8px;
            font-size: 1rem;
            background: white;
        }

        .auth-btn {
            background: linear-gradient(45deg, #28a745, #20c997);
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 8px;
            font-size: 1rem;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .auth-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(40, 167, 69, 0.3);
        }

        .auth-btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .auth-status {
            padding: 15px;
            border-radius: 8px;
            font-size: 0.95rem;
            background: #f8f9fa;
            border: 1px solid #dee2e6;
        }

        /* 主内容区域 */
        .main-content {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 30px;
            margin-top: 30px;
        }

        .content-card {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        }

        .card-title {
            font-size: 1.3rem;
            font-weight: bold;
            color: #333;
            margin-bottom: 20px;
            text-align: center;
            padding-bottom: 10px;
            border-bottom: 2px solid #f0f0f0;
        }

        /* 通知发布表单 */
        .publish-form {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }

        .form-group {
            display: flex;
            flex-direction: column;
        }

        .form-label {
            font-weight: bold;
            margin-bottom: 8px;
            color: #333;
        }

        .form-input {
            padding: 12px;
            border: 2px solid #ddd;
            border-radius: 8px;
            font-size: 1rem;
            transition: border-color 0.3s ease;
        }

        .form-input:focus {
            outline: none;
            border-color: #007bff;
            box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.1);
        }

        .form-textarea {
            min-height: 120px;
            resize: vertical;
        }

        /* 范围选择器 */
        .scope-selector {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 15px;
        }

        .scope-options {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 10px;
            margin-top: 10px;
        }

        .scope-option {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 10px;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .scope-option:hover {
            background: rgba(0, 123, 255, 0.1);
        }

        .scope-option.selected {
            background: rgba(0, 123, 255, 0.15);
            border: 1px solid #007bff;
        }

        .scope-option.disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .scope-checkbox {
            width: 18px;
            height: 18px;
        }

        .scope-label {
            font-size: 0.95rem;
            font-weight: 500;
        }

        .scope-description {
            font-size: 0.8rem;
            color: #666;
            margin-top: 4px;
        }

        /* 发布按钮 */
        .publish-btn {
            background: linear-gradient(45deg, #007bff, #0056b3);
            color: white;
            border: none;
            padding: 15px 30px;
            border-radius: 8px;
            font-size: 1.1rem;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .publish-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 123, 255, 0.3);
        }

        .publish-btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        /* 权限矩阵 */
        .permission-matrix {
            margin-bottom: 20px;
        }

        .matrix-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 0.9rem;
        }

        .matrix-table th,
        .matrix-table td {
            padding: 8px;
            text-align: center;
            border: 1px solid #ddd;
        }

        .matrix-table th {
            background: #f8f9fa;
            font-weight: bold;
        }

        .matrix-table .current-user {
            background: rgba(0, 123, 255, 0.1);
            font-weight: bold;
        }

        .permission-level {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 0.8rem;
            font-weight: bold;
        }

        .level-1 { background: #f8d7da; color: #721c24; } /* 紧急-红色 */
        .level-2 { background: #fff3cd; color: #856404; } /* 重要-橙色 */
        .level-3 { background: #cce5ff; color: #004085; } /* 常规-蓝色 */
        .level-4 { background: #d4edda; color: #155724; } /* 提醒-绿色 */
        .level-0 { background: #e2e3e5; color: #383d41; }

        /* 通知模板选择器 */
        .template-selector {
            margin-bottom: 25px;
            padding: 20px;
            background: rgba(255, 193, 7, 0.08);
            border: 1px solid rgba(255, 193, 7, 0.3);
            border-radius: 12px;
        }

        .template-selector h4 {
            margin-bottom: 15px;
            color: #856404;
            font-size: 1.1rem;
        }

        .template-options {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 10px;
        }

        .template-btn {
            padding: 12px 16px;
            background: linear-gradient(135deg, #fff 0%, #f8f9fa 100%);
            border: 2px solid #007bff;
            border-radius: 8px;
            color: #007bff;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 0.9rem;
            text-align: center;
        }

        .template-btn:hover {
            background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 123, 255, 0.3);
        }

        .template-btn.clear-btn {
            border-color: #dc3545;
            color: #dc3545;
        }

        .template-btn.clear-btn:hover {
            background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
            color: white;
        }

        .template-btn:active {
            transform: translateY(0);
        }

        /* 发布结果 */
        .publish-result {
            margin-top: 20px;
            padding: 15px;
            border-radius: 8px;
            display: none;
        }

        .result-success {
            background: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }

        .result-error {
            background: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }

        .result-warning {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            color: #856404;
        }

        /* 加载状态 */
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.7);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 9999;
        }

        .loading-content {
            background: white;
            padding: 30px;
            border-radius: 15px;
            text-align: center;
            box-shadow: 0 10px 30px rgba(0,0,0,0.3);
        }

        .spinner {
            width: 40px;
            height: 40px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #007bff;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto 15px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* 日志区域 */
        .log-section {
            margin-top: 20px;
        }

        .log-container {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 15px;
            max-height: 300px;
            overflow-y: auto;
            font-family: 'Courier New', monospace;
            font-size: 0.85rem;
        }

        .log-entry {
            margin-bottom: 5px;
            padding: 5px;
            border-radius: 4px;
        }

        .log-info { background: rgba(0, 123, 255, 0.1); }
        .log-success { background: rgba(40, 167, 69, 0.1); }
        .log-warning { background: rgba(255, 193, 7, 0.1); }
        .log-error { background: rgba(220, 53, 69, 0.1); }

        /* 响应式设计增强 */
        @media (max-width: 768px) {
            .main-content {
                grid-template-columns: 1fr;
                gap: 20px;
            }

            .auth-controls {
                grid-template-columns: 1fr;
                gap: 10px;
            }

            .feature-list {
                grid-template-columns: 1fr;
            }

            .scope-options {
                grid-template-columns: 1fr;
            }
            
            .template-options {
                grid-template-columns: 1fr;
            }
            
            .phase-navigation {
                flex-direction: column;
                align-items: stretch;
            }
            
            .phase-nav-item {
                text-align: center;
                margin: 2px 0;
            }
            
            .header h1 {
                font-size: 1.8rem;
            }
            
            .header .subtitle {
                font-size: 1rem;
            }
        }
        
        /* 平板设备适配 */
        @media (max-width: 1024px) and (min-width: 769px) {
            .feature-list {
                grid-template-columns: 1fr;
            }
            
            .template-options {
                grid-template-columns: repeat(2, 1fr);
            }
            
            .auth-controls {
                grid-template-columns: 2fr 1fr 1fr;
            }
        }
        
        /* 大屏幕优化 */
        @media (min-width: 1400px) {
            .container {
                max-width: 1800px;
            }
            
            .main-content {
                grid-template-columns: 1.2fr 0.8fr;
            }
        }
        
        /* 打印样式 */
        @media print {
            .header, .phase-navigation, .auth-section, .loading-overlay {
                display: none !important;
            }
            
            body {
                background: white !important;
            }
            
            .content-card {
                box-shadow: none !important;
                border: 1px solid #ddd;
            }
        }
        
        /* 高对比度支持 */
        @media (prefers-contrast: high) {
            .content-card {
                border: 2px solid #333;
            }
            
            .form-input {
                border-color: #333;
            }
            
            .scope-option {
                border: 1px solid #333;
            }
        }
        
        /* 减少动画支持 */
        @media (prefers-reduced-motion: reduce) {
            *, *::before, *::after {
                animation-duration: 0.01ms !important;
                animation-iteration-count: 1 !important;
                transition-duration: 0.01ms !important;
            }
        }

        /* 工具提示 */
        .tooltip {
            position: relative;
            cursor: help;
        }

        .tooltip:hover::after {
            content: attr(data-tooltip);
            position: absolute;
            bottom: 100%;
            left: 50%;
            transform: translateX(-50%);
            background: #333;
            color: white;
            padding: 8px 12px;
            border-radius: 6px;
            font-size: 0.8rem;
            white-space: nowrap;
            z-index: 1000;
        }

        .d-none {
            display: none !important;
        }
        
        /* 表单验证状态样式 */
        .field-valid {
            border-color: #28a745 !important;
            background-color: rgba(40, 167, 69, 0.1);
        }
        
        .field-invalid {
            border-color: #dc3545 !important;
            background-color: rgba(220, 53, 69, 0.1);
        }
        
        .field-error {
            color: #dc3545;
            font-size: 0.85rem;
            margin-top: 4px;
            font-weight: 500;
        }
        
        /* 按钮加载状态 */
        .auth-btn:disabled,
        .publish-btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
            position: relative;
        }
        
        .auth-btn:disabled::after,
        .publish-btn:disabled::after {
            content: '';
            position: absolute;
            width: 16px;
            height: 16px;
            margin: auto;
            border: 2px solid transparent;
            border-top-color: #ffffff;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 页面头部 -->
        <div class="header">
            <h1>🚀 Phase 7: 范围发布通知测试页面</h1>
            <div class="subtitle">基于Phase6权限矩阵系统的通知发布测试平台</div>
            
            <!-- 功能特性介绍 -->
            <div class="feature-highlight">
                <h3>🎯 核心功能特性</h3>
                <div class="feature-list">
                    <div class="feature-item">
                        <strong>🔐 双重认证集成</strong><br>
                        Mock School API → JWT Token → 主服务验证
                    </div>
                    <div class="feature-item">
                        <strong>📊 智能范围选择</strong><br>
                        基于角色权限动态显示可用发布范围
                    </div>
                    <div class="feature-item">
                        <strong>📝 完整通知发布</strong><br>
                        标题、内容、优先级、范围一体化发布
                    </div>
                    <div class="feature-item">
                        <strong>🛡️ 权限实时验证</strong><br>
                        发布前权限检查，确保合规操作
                    </div>
                    <div class="feature-item">
                        <strong>📈 发布结果分析</strong><br>
                        详细发布日志、错误诊断、成功反馈
                    </div>
                    <div class="feature-item">
                        <strong>🎨 A+用户体验</strong><br>
                        响应式设计、流畅动画、移动端适配
                    </div>
                </div>
            </div>
        </div>

        <!-- 阶段导航 -->
        <div class="phase-navigation">
            <a href="phase1-connection-working.html" class="phase-nav-item">Phase 1: 连接测试</a>
            <a href="phase2-authentication-enhanced.html" class="phase-nav-item">Phase 2: 双重认证</a>
            <a href="phase3-notification-publish.html" class="phase-nav-item">Phase 3: 通知发布</a>
            <a href="phase4-notification-list.html" class="phase-nav-item">Phase 4: 通知列表</a>
            <a href="phase5-notification-approval.html" class="phase-nav-item">Phase 5: 审批工作流</a>
            <a href="phase6-notification-scope.html" class="phase-nav-item">Phase 6: 权限矩阵</a>
            <span class="phase-nav-item current">Phase 7: 范围发布测试</span>
        </div>

        <!-- 认证区域 -->
        <div class="auth-section">
            <div class="auth-controls">
                <select id="roleSelector" class="role-selector">
                    <option value="">请选择用户角色</option>
                    <option value="PRINCIPAL">校长张明 (4级权限-全范围)</option>
                    <option value="ACADEMIC_ADMIN">教务主任李华 (3级权限)</option>
                    <option value="TEACHER">教师王老师 (2级权限)</option>
                    <option value="CLASS_TEACHER">班主任刘老师 (2级权限)</option>
                    <option value="STUDENT">学生张同学 (1级权限)</option>
                </select>
                <button id="authBtn" class="auth-btn">🚀 一键认证</button>
                <button id="clearBtn" class="auth-btn" style="background: linear-gradient(45deg, #dc3545, #c82333);">🗑️ 清除状态</button>
            </div>
            <div id="authStatus" class="auth-status">
                ❌ 未认证 - 请选择角色并点击认证按钮
            </div>
        </div>

        <!-- 主内容区域 -->
        <div class="main-content d-none" id="mainContent">
            <!-- 左侧：通知发布表单 -->
            <div class="content-card">
                <div class="card-title">📝 通知发布中心</div>
                
                <!-- 权限矩阵显示 -->
                <div class="permission-matrix">
                    <h4>🎯 当前用户权限矩阵</h4>
                    <table class="matrix-table">
                        <thead>
                            <tr>
                                <th>范围类型</th>
                                <th>权限级别</th>
                                <th>发布状态</th>
                            </tr>
                        </thead>
                        <tbody id="permissionMatrixBody">
                            <!-- 动态生成权限矩阵 -->
                        </tbody>
                    </table>
                </div>

                <!-- 通知模板选择器 -->
                <div class="template-selector">
                    <h4>📋 快速模板选择</h4>
                    <div class="template-options">
                        <button type="button" class="template-btn" onclick="applyTemplate('emergency')">
                            🚨 紧急通知模板
                        </button>
                        <button type="button" class="template-btn" onclick="applyTemplate('academic')">
                            📚 教务通知模板
                        </button>
                        <button type="button" class="template-btn" onclick="applyTemplate('activity')">
                            🎉 活动通知模板
                        </button>
                        <button type="button" class="template-btn" onclick="applyTemplate('meeting')">
                            🤝 会议通知模板
                        </button>
                        <button type="button" class="template-btn" onclick="applyTemplate('maintenance')">
                            🔧 维护通知模板
                        </button>
                        <button type="button" class="template-btn" onclick="applyTemplate('holiday')">
                            🏖️ 假期通知模板
                        </button>
                        <button type="button" class="template-btn clear-btn" onclick="clearForm()">
                            🗑️ 清空表单
                        </button>
                    </div>
                </div>

                <!-- 通知发布表单 -->
                <form class="publish-form" id="publishForm">
                    <div class="form-group">
                        <label class="form-label">📋 通知标题 *</label>
                        <input type="text" id="notificationTitle" class="form-input" 
                               placeholder="请输入通知标题（必填）" required>
                    </div>

                    <div class="form-group">
                        <label class="form-label">📄 通知内容 *</label>
                        <textarea id="notificationContent" class="form-input form-textarea" 
                                  placeholder="请输入通知详细内容（必填）" required></textarea>
                    </div>

                    <div class="form-group">
                        <label class="form-label">⚡ 优先级别</label>
                        <select id="priorityLevel" class="form-input">
                            <option value="1">🔴 紧急通知 (Level 1)</option>
                            <option value="2">🟠 重要通知 (Level 2)</option>
                            <option value="3" selected>🟡 常规通知 (Level 3)</option>
                            <option value="4">🟢 提醒信息 (Level 4)</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label class="form-label">🎯 发布范围 *</label>
                        <div class="scope-selector">
                            <p style="margin-bottom: 10px; color: #666; font-size: 0.9rem;">
                                根据您的角色权限，可选择以下范围：
                            </p>
                            <div class="scope-options" id="scopeOptions">
                                <!-- 动态生成范围选项 -->
                            </div>
                        </div>
                    </div>

                    <button type="submit" class="publish-btn" id="publishBtn">
                        📤 发布通知
                    </button>
                </form>

                <!-- 发布结果 -->
                <div class="publish-result" id="publishResult">
                    <!-- 动态显示发布结果 -->
                </div>
            </div>

            <!-- 右侧：发布日志和权限信息 -->
            <div class="content-card">
                <div class="card-title">📊 发布监控中心</div>
                
                <!-- 用户信息卡片 -->
                <div id="userInfoCard" style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin-bottom: 20px;">
                    <!-- 动态显示用户信息 -->
                </div>

                <!-- 权限范围统计 -->
                <div id="scopeStatsCard" style="background: #e8f4f8; padding: 15px; border-radius: 8px; margin-bottom: 20px;">
                    <!-- 动态显示权限统计 -->
                </div>

                <!-- 操作日志 -->
                <div class="log-section">
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                        <h4>📋 操作日志</h4>
                        <button onclick="clearLogs()" style="background: #6c757d; color: white; border: none; padding: 5px 10px; border-radius: 4px; font-size: 0.8rem;">清除日志</button>
                    </div>
                    <div class="log-container" id="logContainer">
                        <div class="log-entry log-info">系统已初始化，等待用户认证...</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 加载状态遮罩 -->
    <div class="loading-overlay" id="loadingOverlay">
        <div class="loading-content">
            <div class="spinner"></div>
            <div id="loadingText">正在处理请求...</div>
        </div>
    </div>

    <script>
        // ========================================
        // 全局配置和状态管理
        // ========================================
        
        const API_BASE = 'http://localhost:48081';
        const MOCK_API_BASE = 'http://localhost:48082';

        // 通知模板配置 - 安全版本，避免触发SQL注入检测
        const NOTIFICATION_TEMPLATES = {
            emergency: {
                title: '紧急通知：校园临时安排',
                content: `各位师生：\n\n因重要事务需要，今日下午将进行必要工作安排。\n\n时间安排：今日下午2点至4点\n影响范围：部分区域暂停服务\n\n请大家提前做好准备，合理安排时间。\n\n如有疑问请联系相关部门。\n\n谢谢配合！\n\n校务办公室\n${new Date().toLocaleDateString()}`,
                priority: 4,
                scope: 'SCHOOL_WIDE'
            },
            academic: {
                title: '教务通知：期末考试安排',
                content: `各位同学：\n\n期末考试相关安排通知如下：\n\n考试时间：12月中下旬\n考试地点：详见考试安排表\n\n重要提醒：\n• 请提前30分钟到达考场\n• 携带身份证件和准考证\n• 考试期间请保持安静\n• 诚信考试是基本要求\n\n祝大家考试顺利！\n\n教务处\n${new Date().toLocaleDateString()}`,
                priority: 2,
                scope: 'SCHOOL_WIDE'
            },
            activity: {
                title: '活动通知：校园文化节报名',
                content: `亲爱的同学们：\n\n校园文化节活动即将开始！\n\n活动时间：12月第一周\n报名截止：本月25日\n\n参与项目：\n• 歌唱比赛\n• 舞蹈表演\n• 话剧演出\n• 书画展览\n• 摄影作品\n\n丰富奖项等着大家！\n\n期待您的积极参与！\n\n学生会\n${new Date().toLocaleDateString()}`,
                priority: 3,
                scope: 'SCHOOL_WIDE'
            },
            meeting: {
                title: '会议通知：月度工作例会',
                content: `各位同事：\n\n定于本月26日上午9点召开月度工作例会。\n\n会议地点：会议室A301\n参会人员：全体教职工\n\n议程安排：\n1. 上月工作总结\n2. 本月计划部署\n3. 重点项目讨论\n4. 其他重要事项\n\n请各部门准备相关材料，准时参会。\n\n办公室\n${new Date().toLocaleDateString()}`,
                priority: 2,
                scope: 'DEPARTMENT'
            },
            maintenance: {
                title: '设备通知：例行检查安排',
                content: `通知：\n\n为确保设备正常运行，安排例行检查工作。\n\n检查时间：本周三下午2点至5点\n影响区域：实验楼A区\n\n检查内容：\n• 空调设施检查\n• 投影设备检修\n• 网络连接检测\n• 消防设施检查\n\n检查期间请勿使用相关设备。\n\n感谢配合！\n\n后勤服务中心\n${new Date().toLocaleDateString()}`,
                priority: 2,
                scope: 'DEPARTMENT'
            },
            holiday: {
                title: '假期通知：国庆节放假安排',
                content: `通知：\n\n根据国家规定，国庆节放假安排如下：\n\n放假时间：10月1日至7日共7天\n调休安排：10月8日周六正常上班\n\n假期注意事项：\n• 注意人身和财产安全\n• 遵守相关防护要求\n• 合理安排出行计划\n• 保持通讯畅通\n\n值班安排另行通知。\n\n祝大家节日快乐！\n\n行政办公室\n${new Date().toLocaleDateString()}`,
                priority: 1,
                scope: 'SCHOOL_WIDE'
            }
        };
        
        // 当前状态
        let currentUser = null;
        let currentToken = null;
        let currentAvailableScopes = [];
        let currentSelectedScope = null;
        
        // 角色账号配置（继承自Phase6）
        const roleAccounts = {
            'PRINCIPAL': {
                employeeId: 'PRINCIPAL_001',
                name: 'Principal-Zhang',
                password: 'admin123',
                displayName: '校长张明'
            },
            'ACADEMIC_ADMIN': {
                employeeId: 'ACADEMIC_ADMIN_001', 
                name: 'Director-Li',
                password: 'admin123',
                displayName: '教务主任李华'
            },
            'TEACHER': {
                employeeId: 'TEACHER_001',
                name: 'Teacher-Wang',
                password: 'admin123',
                displayName: '教师王老师'
            },
            'CLASS_TEACHER': {
                employeeId: 'CLASS_TEACHER_001',
                name: 'ClassTeacher-Liu',
                password: 'admin123',
                displayName: '班主任刘老师'
            },
            'STUDENT': {
                employeeId: 'STUDENT_001',
                name: 'Student-Zhang',
                password: 'admin123',
                displayName: '学生张同学'
            }
        };

        // 增强权限矩阵（继承自Phase6）
        const ENHANCED_PERMISSION_MATRIX = {
            'PRINCIPAL': {
                'SCHOOL_WIDE': { level: 1, description: '全校范围', canPublish: true }, // 校长可发布1-4级所有通知
                'DEPARTMENT': { level: 1, description: '部门范围', canPublish: true },
                'CLASS': { level: 1, description: '班级范围', canPublish: true },
                'GRADE': { level: 1, description: '年级范围', canPublish: true }
            },
            'ACADEMIC_ADMIN': {
                'SCHOOL_WIDE': { level: 2, description: '全校范围', canPublish: true }, // 教务主任可发布2-4级，1级需审批
                'DEPARTMENT': { level: 2, description: '部门范围', canPublish: true },
                'GRADE': { level: 2, description: '年级范围', canPublish: true }
            },
            'TEACHER': {
                'DEPARTMENT': { level: 3, description: '部门范围', canPublish: true }, // 教师可发布3-4级
                'CLASS': { level: 3, description: '班级范围', canPublish: true }
            },
            'CLASS_TEACHER': {
                'CLASS': { level: 3, description: '班级范围', canPublish: true }, // 班主任可发布3-4级
                'GRADE': { level: 3, description: '年级范围', canPublish: true }
            },
            'STUDENT': {
                'CLASS': { level: 4, description: '班级范围', canPublish: true } // 学生只能发布4级提醒
            }
        };

        // 范围配置
        const SCOPE_CONFIG = {
            'SCHOOL_WIDE': {
                name: '全校通知',
                description: '面向全校师生的重要通知',
                icon: '🏫'
            },
            'DEPARTMENT': {
                name: '部门通知',
                description: '面向特定部门的工作通知',
                icon: '🏢'
            },
            'CLASS': {
                name: '班级通知',
                description: '面向特定班级的日常通知',
                icon: '👨‍🎓'
            },
            'GRADE': {
                name: '年级通知',
                description: '面向特定年级的通知',
                icon: '📚'
            }
        };

        // ========================================
        // 工具函数
        // ========================================
        
        function addLog(message, type = 'info') {
            const logContainer = document.getElementById('logContainer');
            const logEntry = document.createElement('div');
            logEntry.className = `log-entry log-${type}`;
            
            const timestamp = new Date().toLocaleTimeString();
            logEntry.textContent = `[${timestamp}] ${message}`;
            
            logContainer.appendChild(logEntry);
            logContainer.scrollTop = logContainer.scrollHeight;
        }

        function clearLogs() {
            const logContainer = document.getElementById('logContainer');
            logContainer.innerHTML = '<div class="log-entry log-info">日志已清除</div>';
        }

        function showLoadingState(text = '正在处理请求...') {
            document.getElementById('loadingText').textContent = text;
            document.getElementById('loadingOverlay').style.display = 'flex';
        }

        function hideLoadingState() {
            document.getElementById('loadingOverlay').style.display = 'none';
        }

        function showResult(message, type = 'success', details = null, autoHide = null) {
            const resultDiv = document.getElementById('publishResult');
            resultDiv.className = `publish-result result-${type}`;
            
            let content = `<strong>${message}</strong>`;
            if (details) {
                content += `<div style="margin-top: 10px; font-size: 0.9rem;">${details}</div>`;
            }
            
            // 添加操作建议
            if (type === 'error') {
                content += `<div style="margin-top: 15px; padding: 10px; background: rgba(0,0,0,0.1); border-radius: 4px; font-size: 0.85rem;">
                    <strong>💡 建议操作：</strong><br>
                    • 检查网络连接状态<br>
                    • 确认认证状态是否有效<br>
                    • 重新选择角色并认证<br>
                    • 如问题持续，请联系系统管理员
                </div>`;
            } else if (type === 'warning') {
                content += `<div style="margin-top: 10px; font-size: 0.85rem; color: #856404;">
                    <strong>📋 请注意：</strong>此通知将在审批通过后正式发布
                </div>`;
            }
            
            resultDiv.innerHTML = content;
            resultDiv.style.display = 'block';
            
            // 滚动到结果区域
            resultDiv.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
            
            // 自动隐藏逻辑增强
            const hideDelay = autoHide || (type === 'success' ? 6000 : type === 'warning' ? 8000 : null);
            if (hideDelay) {
                setTimeout(() => {
                    resultDiv.style.display = 'none';
                }, hideDelay);
            }
        }

        // ========================================
        // API工具函数 - 增强版本
        // ========================================
        
        // 增强的带超时和重试的fetch封装
        async function fetchWithRetry(url, options = {}, maxRetries = 2, timeout = 10000) {
            const controller = new AbortController();
            let timeoutId;
            
            for (let attempt = 0; attempt <= maxRetries; attempt++) {
                try {
                    // 为每次尝试设置独立的超时
                    timeoutId = setTimeout(() => controller.abort(), timeout);
                    
                    const response = await fetch(url, {
                        ...options,
                        signal: controller.signal
                    });
                    
                    clearTimeout(timeoutId);
                    
                    // 检查401状态码，自动清理认证状态
                    if (response.status === 401) {
                        addLog(`⚠️ 认证已过期或无效，自动清理状态`, 'warning');
                        clearAuthStatus();
                        throw new Error('认证已过期，请重新登录');
                    }
                    
                    // 检查403状态码，权限不足
                    if (response.status === 403) {
                        addLog(`🚫 权限不足，无法访问此资源`, 'error');
                        throw new Error('权限不足，请检查您的角色权限设置');
                    }
                    
                    // 检查服务器错误
                    if (response.status >= 500) {
                        const errorText = `服务器内部错误 (HTTP ${response.status})`;
                        addLog(`💥 ${errorText}`, 'error');
                        throw new Error(errorText);
                    }
                    
                    return response;
                    
                } catch (error) {
                    if (timeoutId) clearTimeout(timeoutId);
                    
                    // 超时处理
                    if (error.name === 'AbortError') {
                        const timeoutError = `请求超时 (${timeout}ms)`;
                        addLog(`⏰ ${timeoutError}: ${url}`, 'warning');
                        
                        if (attempt < maxRetries) {
                            addLog(`🔄 正在重试 (${attempt + 1}/${maxRetries + 1})...`, 'info');
                            await new Promise(resolve => setTimeout(resolve, Math.min(2000, 1000 * (attempt + 1))));
                            continue;
                        }
                        throw new Error(`网络请求超时，请检查网络连接后重试`);
                    }
                    
                    // 网络错误处理
                    if (error.message.includes('fetch') || error.message.includes('network') || error.message.includes('Failed to fetch')) {
                        const networkError = '网络连接异常';
                        addLog(`🌐 ${networkError}`, 'warning');
                        
                        if (attempt < maxRetries) {
                            addLog(`🔄 网络重试 (${attempt + 1}/${maxRetries + 1})...`, 'info');
                            await new Promise(resolve => setTimeout(resolve, Math.min(3000, 1500 * (attempt + 1))));
                            continue;
                        }
                        throw new Error('网络连接失败，请检查网络状态后重试');
                    }
                    
                    // 其他错误直接抛出，不重试
                    throw error;
                }
            }
        }
        
        // 安全的JSON解析
        async function safeJsonParse(response) {
            try {
                const text = await response.text();
                if (!text.trim()) {
                    throw new Error('服务器返回空响应');
                }
                return JSON.parse(text);
            } catch (error) {
                if (error instanceof SyntaxError) {
                    throw new Error('服务器返回的不是有效的JSON格式');
                }
                throw error;
            }
        }
        
        // ========================================
        // 认证相关函数 - 增强版本
        // ========================================
        
        async function authenticateUser() {
            const roleSelector = document.getElementById('roleSelector');
            const authBtn = document.getElementById('authBtn');
            const authStatus = document.getElementById('authStatus');
            
            const selectedRole = roleSelector.value;
            if (!selectedRole) {
                showResult('请先选择用户角色', 'error');
                return;
            }
            
            // 验证角色切换
            if (!validateRoleSwitch()) {
                return;
            }
            
            // 防止重复操作
            if (isOperationInProgress) {
                addLog('⚠️ 认证操作正在进行中，请等待...', 'warning');
                return;
            }

            const success = setOperationInProgress(true, 'auth');
            if (!success) {
                return; // 操作频率受限
            }
            
            try {
                showLoadingState('正在进行双重认证...');
                addLog('🚀 开始双重认证流程', 'info');
                
                const account = roleAccounts[selectedRole];
                addLog(`👤 选择角色: ${account.displayName} (${selectedRole})`, 'info');
                
                // 第一步：Mock School API身份认证
                addLog('🔐 第一步：Mock School API身份认证', 'info');
                
                const authResponse = await fetchWithRetry(`${MOCK_API_BASE}/mock-school-api/auth/authenticate`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        employeeId: account.employeeId,
                        name: account.name,
                        password: account.password
                    })
                }, 2, 15000); // 认证请求允许更长超时时间
                
                addLog(`📤 认证API请求: POST ${MOCK_API_BASE}/mock-school-api/auth/authenticate`, 'info');
                addLog(`📥 认证API响应状态: ${authResponse.status} ${authResponse.statusText}`, 'info');
                
                if (!authResponse.ok) {
                    let errorMessage = `HTTP ${authResponse.status}`;
                    try {
                        const errorData = await safeJsonParse(authResponse);
                        errorMessage += ` - ${errorData.message || errorData.msg || '认证失败'}`;
                    } catch {
                        errorMessage += ` - Mock School API认证服务不可用`;
                    }
                    throw new Error(`Mock School API认证失败: ${errorMessage}`);
                }
                
                const authResult = await safeJsonParse(authResponse);
                
                if (!authResult.success || !authResult.data) {
                    throw new Error(authResult.message || 'Mock School API认证失败');
                }
                
                // 保存认证信息
                currentUser = authResult.data;
                currentToken = authResult.data.accessToken;
                
                if (!currentToken) {
                    throw new Error('认证成功但未获取到访问令牌');
                }
                
                addLog('✅ 第一步认证完成：获得JWT访问令牌', 'success');
                addLog(`👤 用户信息: ${currentUser.realName || currentUser.username} (${currentUser.roleCode})`, 'info');
                
                // 第二步：获取用户可用范围
                await fetchAvailableScopes();
                
                // 更新UI状态
                updateAuthStatus();
                updateUserInterface();
                
                // 显示主内容
                document.getElementById('mainContent').classList.remove('d-none');
                
                addLog(`🎉 双重认证流程完成！用户: ${currentUser.realName || currentUser.username}`, 'success');
                
            } catch (error) {
                addLog(`❌ 认证失败: ${error.message}`, 'error');
                
                authStatus.textContent = `❌ 认证失败: ${error.message}`;
                authStatus.style.background = '#f8d7da';
                authStatus.style.color = '#721c24';
                
                showResult(`认证失败：${error.message}`, 'error');
                
            } finally {
                hideLoadingState();
                setOperationInProgress(false);
            }
        }

        async function fetchAvailableScopes() {
            addLog('🔍 第二步：获取用户可用范围权限', 'info');
            
            const cleanToken = currentToken.startsWith('Bearer ') ? currentToken.substring(7) : currentToken;
            
            try {
                const response = await fetchWithRetry(`${API_BASE}/admin-api/test/notification/api/available-scopes`, {
                    method: 'GET',
                    headers: {
                        'Authorization': `Bearer ${cleanToken}`,
                        'tenant-id': '1',
                        'Content-Type': 'application/json'
                    }
                }, 2, 12000);
                
                addLog(`📤 API请求: GET /admin-api/test/notification/api/available-scopes`, 'info');
                addLog(`📥 API响应状态: ${response.status} ${response.statusText}`, 'info');
                
                if (response.ok) {
                    const result = await safeJsonParse(response);
                    
                    if (result.code === 0 && result.data) {
                        const apiScopes = result.data.availableScopes || [];
                        
                        // 处理API返回的范围数据
                        if (Array.isArray(apiScopes) && apiScopes.length > 0 && typeof apiScopes[0] === 'object') {
                            currentAvailableScopes = apiScopes.map(scope => scope.code);
                        } else {
                            currentAvailableScopes = apiScopes;
                        }
                        
                        addLog(`✅ API获取成功: 可用范围=${currentAvailableScopes.length}个`, 'success');
                        addLog(`🎯 可用范围列表: [${currentAvailableScopes.join(', ')}]`, 'success');
                        
                    } else {
                        throw new Error(result.message || 'API返回数据格式错误');
                    }
                } else {
                    throw new Error(`API请求失败: HTTP ${response.status}`);
                }
                
            } catch (error) {
                addLog(`⚠️ API获取失败，使用本地配置: ${error.message}`, 'warning');
                
                // 使用本地权限矩阵作为备用
                const localPermissions = ENHANCED_PERMISSION_MATRIX[currentUser.roleCode] || {};
                currentAvailableScopes = Object.keys(localPermissions).filter(scope => 
                    localPermissions[scope].canPublish
                );
                
                addLog(`🔧 本地配置范围: [${currentAvailableScopes.join(', ')}]`, 'info');
            }
        }

        function updateAuthStatus() {
            const authStatus = document.getElementById('authStatus');
            authStatus.textContent = `✅ 认证成功 - ${currentUser.realName || currentUser.username} (${roleAccounts[currentUser.roleCode]?.displayName})`;
            authStatus.style.background = '#d4edda';
            authStatus.style.color = '#155724';
        }

        // 增强的清理认证状态函数
        function clearAuthStatus() {
            // 强化清理与进一步验证
            const wasAuthenticated = currentUser !== null;
            
            currentUser = null;
            currentToken = null;
            currentAvailableScopes = [];
            currentSelectedScope = null;
            
            const authStatus = document.getElementById('authStatus');
            authStatus.textContent = '❌ 未认证 - 请选择角色并点击认证按钮';
            authStatus.style.background = '#f8f9fa';
            authStatus.style.color = '#333';
            
            // 隐藏主内容区域
            document.getElementById('mainContent').classList.add('d-none');
            document.getElementById('roleSelector').value = '';
            
            // 重置表单状态
            resetFormState();
            
            // 清理发布结果
            const publishResult = document.getElementById('publishResult');
            if (publishResult) {
                publishResult.style.display = 'none';
            }
            
            // 重置操作状态
            if (isOperationInProgress) {
                setOperationInProgress(false);
            }
            
            // 清除可能的定时器
            clearTimeout(window.authTimeout);
            
            if (wasAuthenticated) {
                addLog('🗑️ 认证状态已完全清除，所有用户数据已重置', 'warning');
                showResult('🔄 认证状态已清除', 'info', '请重新选择角色并认证以继续使用系统', 3000);
            } else {
                addLog('🗑️ 认证状态已清除', 'info');
            }
        }
        
        // 重置表单状态
        function resetFormState() {
            const publishForm = document.getElementById('publishForm');
            if (publishForm) {
                publishForm.reset();
                // 重置表单样式
                publishForm.style.background = '';
                publishForm.style.border = '';
            }
            
            // 重置按钮状态
            const publishBtn = document.getElementById('publishBtn');
            if (publishBtn) {
                publishBtn.disabled = false;
                publishBtn.textContent = '📤 发布通知';
            }
            
            const authBtn = document.getElementById('authBtn');
            if (authBtn) {
                authBtn.disabled = false;
                authBtn.textContent = '🚀 一键认证';
            }
        }
        
        // 增强的角色切换验证
        function validateRoleSwitch() {
            const roleSelector = document.getElementById('roleSelector');
            const selectedRole = roleSelector.value;
            
            // 如果已经认证且选择了不同角色，提醒重新认证
            if (currentUser && currentUser.roleCode !== selectedRole && selectedRole) {
                const currentRoleName = roleAccounts[currentUser.roleCode]?.displayName || currentUser.roleCode;
                const newRoleName = roleAccounts[selectedRole]?.displayName || selectedRole;
                
                addLog(`⚠️ 角色切换检测: ${currentRoleName} → ${newRoleName}，需要重新认证`, 'warning');
                
                // 显示确认提示
                showResult(
                    '🔄 角色切换确认', 
                    'warning', 
                    `正在从 <strong>${currentRoleName}</strong> 切换到 <strong>${newRoleName}</strong><br>
                     当前认证状态将被清除，请重新认证以获取新角色权限`, 
                     4000
                );
                
                // 自动清理之前的认证状态
                setTimeout(() => {
                    clearAuthStatus();
                    addLog(`🔄 角色切换完成，请使用新角色进行认证`, 'info');
                }, 1000);
                
                return false;
            }
            
            return true;
        }

        // ========================================
        // UI更新函数
        // ========================================
        
        function updateUserInterface() {
            updateUserInfoCard();
            updateScopeStatsCard();
            updatePermissionMatrix();
            updateScopeOptions();
        }

        function updateUserInfoCard() {
            const userInfoCard = document.getElementById('userInfoCard');
            const roleInfo = roleAccounts[currentUser.roleCode];
            
            userInfoCard.innerHTML = `
                <h4>👤 当前用户信息</h4>
                <div style="margin-top: 10px;">
                    <strong>姓名：</strong>${currentUser.realName || currentUser.username}<br>
                    <strong>角色：</strong>${roleInfo?.displayName || currentUser.roleCode}<br>
                    <strong>工号：</strong>${roleInfo?.employeeId || 'N/A'}<br>
                    <strong>权限级别：</strong>${getRoleMaxLevel(currentUser.roleCode)}级<br>
                    <strong>可用范围：</strong>${currentAvailableScopes.length}个
                </div>
            `;
        }

        function updateScopeStatsCard() {
            const scopeStatsCard = document.getElementById('scopeStatsCard');
            const permissions = ENHANCED_PERMISSION_MATRIX[currentUser.roleCode] || {};
            
            let statsHtml = '<h4>📊 权限范围统计</h4><div style="margin-top: 10px;">';
            
            currentAvailableScopes.forEach(scope => {
                const permission = permissions[scope];
                const config = SCOPE_CONFIG[scope];
                
                if (permission && config) {
                    statsHtml += `
                        <div style="margin-bottom: 8px; padding: 8px; background: rgba(0,123,255,0.1); border-radius: 4px;">
                            <strong>${config.icon} ${config.name}</strong> 
                            <span class="permission-level level-${permission.level}">Level ${permission.level}</span>
                            <div style="font-size: 0.8rem; color: #666; margin-top: 4px;">${config.description}</div>
                        </div>
                    `;
                }
            });
            
            statsHtml += '</div>';
            scopeStatsCard.innerHTML = statsHtml;
        }

        function updatePermissionMatrix() {
            const matrixBody = document.getElementById('permissionMatrixBody');
            const permissions = ENHANCED_PERMISSION_MATRIX[currentUser.roleCode] || {};
            
            let matrixHtml = '';
            
            // 按优先级排序范围
            const sortedScopes = ['SCHOOL_WIDE', 'DEPARTMENT', 'GRADE', 'CLASS'];
            
            sortedScopes.forEach(scope => {
                const permission = permissions[scope];
                const config = SCOPE_CONFIG[scope];
                const isAvailable = currentAvailableScopes.includes(scope);
                
                matrixHtml += `
                    <tr ${isAvailable ? 'class="current-user"' : ''}>
                        <td>${config?.icon || '📋'} ${config?.name || scope}</td>
                        <td>
                            ${permission ? 
                                `<span class="permission-level level-${permission.level}">Level ${permission.level}</span>` : 
                                `<span class="permission-level level-0">无权限</span>`
                            }
                        </td>
                        <td>
                            ${isAvailable ? 
                                '<span style="color: #28a745;">✅ 可发布</span>' : 
                                '<span style="color: #dc3545;">❌ 禁止</span>'
                            }
                        </td>
                    </tr>
                `;
            });
            
            matrixBody.innerHTML = matrixHtml;
        }

        function updateScopeOptions() {
            const scopeOptions = document.getElementById('scopeOptions');
            const permissions = ENHANCED_PERMISSION_MATRIX[currentUser.roleCode] || {};
            
            let optionsHtml = '';
            
            // 生成可用范围选项
            currentAvailableScopes.forEach(scope => {
                const permission = permissions[scope];
                const config = SCOPE_CONFIG[scope];
                
                if (permission && config) {
                    optionsHtml += `
                        <div class="scope-option" onclick="selectScope('${scope}')">
                            <input type="radio" name="scope" value="${scope}" class="scope-checkbox" id="scope_${scope}">
                            <label for="scope_${scope}" class="scope-label">
                                ${config.icon} ${config.name}
                                <span class="permission-level level-${permission.level}">Level ${permission.level}</span>
                                <div class="scope-description">${config.description}</div>
                            </label>
                        </div>
                    `;
                }
            });
            
            if (optionsHtml === '') {
                optionsHtml = '<div style="color: #dc3545; text-align: center; padding: 20px;">当前角色无可用发布范围</div>';
            }
            
            scopeOptions.innerHTML = optionsHtml;
        }

        function selectScope(scope) {
            // 清除之前的选择
            document.querySelectorAll('.scope-option').forEach(option => {
                option.classList.remove('selected');
            });
            
            // 设置新选择
            const selectedOption = document.querySelector(`#scope_${scope}`);
            if (selectedOption) {
                selectedOption.checked = true;
                selectedOption.closest('.scope-option').classList.add('selected');
                currentSelectedScope = scope;
                
                // 清除范围验证错误状态
                const scopeSelector = document.querySelector('.scope-selector');
                if (scopeSelector) {
                    scopeSelector.style.borderColor = '#28a745';
                    scopeSelector.style.backgroundColor = 'rgba(40, 167, 69, 0.1)';
                    
                    const existingError = scopeSelector.parentNode.querySelector('.scope-error');
                    if (existingError) {
                        existingError.remove();
                    }
                }
                
                addLog(`🎯 选择发布范围: ${SCOPE_CONFIG[scope]?.name} (${scope})`, 'info');
                
                // 立即进行范围验证
                setTimeout(() => {
                    validateFormField('', 'scope');
                }, 100);
            }
        }

        // ========================================
        // 表单验证增强函数
        // ========================================
        
        // 实时表单验证增强
        function validateFormField(fieldId, validationType = 'text') {
            // scope验证的特殊处理
            if (validationType === 'scope') {
                let isValid = true;
                let errorMessage = '';
                
                if (!currentSelectedScope) {
                    isValid = false;
                    errorMessage = '请选择发布范围';
                    addLog('❌ 范围验证: 未选择发布范围', 'error');
                } else if (!currentAvailableScopes.includes(currentSelectedScope)) {
                    isValid = false;
                    errorMessage = '所选范围超出您的权限';
                    addLog(`❌ 范围验证: 所选范围 ${currentSelectedScope} 不在可用范围 [${currentAvailableScopes.join(', ')}] 中`, 'error');
                } else {
                    addLog(`✅ 范围验证: ${currentSelectedScope} 在可用范围内`, 'success');
                }
                
                // 显示范围验证错误
                const scopeSelector = document.querySelector('.scope-selector');
                if (scopeSelector) {
                    if (!isValid) {
                        scopeSelector.style.borderColor = '#dc3545';
                        scopeSelector.style.backgroundColor = 'rgba(220, 53, 69, 0.1)';
                        
                        // 添加错误消息到范围选择器
                        let existingError = scopeSelector.parentNode.querySelector('.scope-error');
                        if (existingError) {
                            existingError.remove();
                        }
                        
                        const errorDiv = document.createElement('div');
                        errorDiv.className = 'scope-error field-error';
                        errorDiv.style.cssText = 'color: #dc3545; font-size: 0.85rem; margin-top: 4px;';
                        errorDiv.textContent = errorMessage;
                        scopeSelector.parentNode.appendChild(errorDiv);
                    } else {
                        scopeSelector.style.borderColor = '#28a745';
                        scopeSelector.style.backgroundColor = 'rgba(40, 167, 69, 0.1)';
                        
                        const existingError = scopeSelector.parentNode.querySelector('.scope-error');
                        if (existingError) {
                            existingError.remove();
                        }
                    }
                }
                
                return isValid;
            }
            
            // 常规字段验证
            const field = document.getElementById(fieldId);
            if (!field) {
                addLog(`❌ 验证失败: 字段 ${fieldId} 不存在`, 'error');
                return false;
            }
            
            const value = field.value.trim();
            let isValid = true;
            let errorMessage = '';
            
            switch (validationType) {
                case 'title':
                    if (!value) {
                        isValid = false;
                        errorMessage = '请输入通知标题';
                        addLog('❌ 标题验证: 标题为空', 'error');
                    } else if (value.length < 2) {
                        isValid = false;
                        errorMessage = '标题至少需要2个字符';
                        addLog(`❌ 标题验证: 标题过短 (${value.length}字符)`, 'error');
                    } else if (value.length > 100) {
                        isValid = false;
                        errorMessage = '标题不能超过100个字符';
                        addLog(`❌ 标题验证: 标题过长 (${value.length}字符)`, 'error');
                    } else if (!/^[\u4e00-\u9fa5\w\s\-、，！？：；""''（）【】《》…]+$/.test(value)) {
                        isValid = false;
                        errorMessage = '标题包含非法字符';
                        addLog('❌ 标题验证: 标题包含非法字符', 'error');
                    } else {
                        addLog(`✅ 标题验证: 通过 (${value.length}字符)`, 'success');
                    }
                    break;
                    
                case 'content':
                    if (!value) {
                        isValid = false;
                        errorMessage = '请输入通知内容';
                        addLog('❌ 内容验证: 内容为空', 'error');
                    } else if (value.length < 5) {
                        isValid = false;
                        errorMessage = '内容至少需要5个字符';
                        addLog(`❌ 内容验证: 内容过短 (${value.length}字符)`, 'error');
                    } else if (value.length > 5000) {
                        isValid = false;
                        errorMessage = '内容不能超过5000个字符';
                        addLog(`❌ 内容验证: 内容过长 (${value.length}字符)`, 'error');
                    } else {
                        addLog(`✅ 内容验证: 通过 (${value.length}字符)`, 'success');
                    }
                    break;
            }
            
            // 更新字段状态
            updateFieldValidationState(field, isValid, errorMessage);
            return isValid;
        }
        
        // 更新字段验证状态
        function updateFieldValidationState(field, isValid, errorMessage) {
            // 移除旧的验证状态
            field.classList.remove('field-valid', 'field-invalid');
            
            // 移除旧的错误消息
            const existingError = field.parentNode.querySelector('.field-error');
            if (existingError) {
                existingError.remove();
            }
            
            if (!isValid && errorMessage) {
                // 添加错误样式
                field.classList.add('field-invalid');
                field.style.borderColor = '#dc3545';
                
                // 添加错误消息
                const errorDiv = document.createElement('div');
                errorDiv.className = 'field-error';
                errorDiv.style.cssText = 'color: #dc3545; font-size: 0.85rem; margin-top: 4px;';
                errorDiv.textContent = errorMessage;
                field.parentNode.appendChild(errorDiv);
                
            } else if (field.value.trim()) {
                // 添加成功样式
                field.classList.add('field-valid');
                field.style.borderColor = '#28a745';
            } else {
                // 重置默认样式
                field.style.borderColor = '';
            }
        }
        
        // 全表单验证增强 - 详细错误日志
        function validateCompleteForm() {
            addLog('🔍 开始全表单验证...', 'info');
            
            const titleValid = validateFormField('notificationTitle', 'title');
            const contentValid = validateFormField('notificationContent', 'content');
            const scopeValid = validateFormField('', 'scope'); // scope特殊处理
            
            addLog(`📝 标题验证: ${titleValid ? '✅ 通过' : '❌ 失败'}`, titleValid ? 'success' : 'error');
            addLog(`📄 内容验证: ${contentValid ? '✅ 通过' : '❌ 失败'}`, contentValid ? 'success' : 'error');
            addLog(`🎯 范围验证: ${scopeValid ? '✅ 通过' : '❌ 失败'}`, scopeValid ? 'success' : 'error');
            
            // 调试信息：显示当前表单值
            const title = document.getElementById('notificationTitle').value.trim();
            const content = document.getElementById('notificationContent').value.trim();
            addLog(`📋 当前表单值 - 标题: "${title.substring(0, 30)}${title.length > 30 ? '...' : ''}", 内容: ${content.length}字符, 范围: ${currentSelectedScope || '未选择'}`, 'info');
            
            // 校验通知级别权限
            const priorityLevel = document.getElementById('priorityLevel').value;
            const permissions = ENHANCED_PERMISSION_MATRIX[currentUser?.roleCode] || {};
            const scopePermission = permissions[currentSelectedScope];
            
            let levelValid = true;
            if (scopePermission && parseInt(priorityLevel) < scopePermission.level) {
                // 特殊情况：教务主任发布1级允许但需要审批
                if (!(currentUser?.roleCode === 'ACADEMIC_ADMIN' && parseInt(priorityLevel) === 1)) {
                    levelValid = false;
                    const levelNames = {1: '紧急', 2: '重要', 3: '常规', 4: '提醒'};
                    const errorMsg = `权限不足：您只能发布${scopePermission.level}-4级通知，无法发布${priorityLevel}级(${levelNames[priorityLevel]})通知`;
                    addLog(`❌ 级别验证: ${errorMsg}`, 'error');
                    showResult(errorMsg, 'error');
                }
            }
            
            addLog(`⚡ 级别验证: ${levelValid ? '✅ 通过' : '❌ 失败'} (请求级别:${priorityLevel}, 最高权限:${scopePermission?.level || 'N/A'})`, levelValid ? 'success' : 'error');
            
            const overallValid = titleValid && contentValid && scopeValid && levelValid;
            addLog(`🎯 全表单验证结果: ${overallValid ? '✅ 全部通过' : '❌ 有错误需要修复'}`, overallValid ? 'success' : 'error');
            
            return overallValid;
        }
        
        // 按钮状态管理增强 - 支持重复操作保护
        let isOperationInProgress = false;
        let lastOperationTime = 0;
        const MIN_OPERATION_INTERVAL = 2000; // 最小操作间隔2秒
        
        function setOperationInProgress(inProgress, operationType = 'default') {
            // 检查操作频率限制
            if (inProgress) {
                const now = Date.now();
                if (now - lastOperationTime < MIN_OPERATION_INTERVAL) {
                    addLog(`⚠️ 操作过于频繁，请等待 ${Math.ceil((MIN_OPERATION_INTERVAL - (now - lastOperationTime)) / 1000)} 秒`, 'warning');
                    return false;
                }
                lastOperationTime = now;
            }
            
            isOperationInProgress = inProgress;
            
            const authBtn = document.getElementById('authBtn');
            const publishBtn = document.getElementById('publishBtn');
            const clearBtn = document.getElementById('clearBtn');
            const roleSelector = document.getElementById('roleSelector');
            
            if (inProgress) {
                // 禁用所有交互元素
                authBtn.disabled = true;
                publishBtn.disabled = true;
                clearBtn.disabled = true;
                roleSelector.disabled = true;
                
                // 设置加载状态和文本
                if (operationType === 'auth') {
                    authBtn.textContent = '🔄 认证中...';
                    authBtn.style.opacity = '0.7';
                } else if (operationType === 'publish') {
                    publishBtn.textContent = '📤 发布中...';
                    publishBtn.style.opacity = '0.7';
                }
                
                // 禁用表单输入和模板按钮
                document.querySelectorAll('#publishForm input, #publishForm textarea, #publishForm select').forEach(field => {
                    field.disabled = true;
                    field.style.opacity = '0.6';
                });
                
                document.querySelectorAll('.template-btn').forEach(btn => {
                    btn.disabled = true;
                    btn.style.opacity = '0.5';
                    btn.style.cursor = 'not-allowed';
                });
                
            } else {
                // 恢复按钮状态
                roleSelector.disabled = false;
                
                if (!currentUser) {
                    authBtn.disabled = false;
                    publishBtn.disabled = true;
                } else {
                    authBtn.disabled = false;
                    publishBtn.disabled = false;
                }
                clearBtn.disabled = false;
                
                // 恢复按钮文本和样式
                authBtn.textContent = '🚀 一键认证';
                authBtn.style.opacity = '';
                publishBtn.textContent = '📤 发布通知';
                publishBtn.style.opacity = '';
                
                // 恢复表单输入
                document.querySelectorAll('#publishForm input, #publishForm textarea, #publishForm select').forEach(field => {
                    field.disabled = false;
                    field.style.opacity = '';
                });
                
                // 恢复模板按钮
                document.querySelectorAll('.template-btn').forEach(btn => {
                    btn.disabled = false;
                    btn.style.opacity = '';
                    btn.style.cursor = '';
                });
            }
            
            return true;
        }
        
        // ========================================
        // 通知发布函数 - 增强版本
        // ========================================
        
        async function publishNotification(event) {
            event.preventDefault();
            
            // 防止重复提交
            if (isOperationInProgress) {
                addLog('⚠️ 发布操作正在进行中，请等待...', 'warning');
                showResult('⏳ 请等待当前操作完成', 'warning', null, 3000);
                return;
            }
            
            // 全表单验证
            if (!validateCompleteForm()) {
                addLog('❌ 表单验证失败，请检查输入内容', 'error');
                showResult('📝 表单填写有误', 'error', '请检查标题、内容和发布范围是否正确填写', 5000);
                return;
            }
            
            // 获取表单数据
            const title = document.getElementById('notificationTitle').value.trim();
            const content = document.getElementById('notificationContent').value.trim();
            const priority = document.getElementById('priorityLevel').value;
            
            // 验证表单
            if (!title) {
                showResult('请输入通知标题', 'error');
                return;
            }
            
            if (!content) {
                showResult('请输入通知内容', 'error');
                return;
            }
            
            if (!currentSelectedScope) {
                showResult('请选择发布范围', 'error');
                return;
            }
            
            // 验证权限
            if (!currentAvailableScopes.includes(currentSelectedScope)) {
                showResult('您没有权限发布到所选范围', 'error');
                return;
            }
            
            // 验证通知级别权限
            const permissions = ENHANCED_PERMISSION_MATRIX[currentUser.roleCode] || {};
            const scopePermission = permissions[currentSelectedScope];
            const requestedLevel = parseInt(priority);
            
            if (!scopePermission) {
                showResult('无法获取范围权限信息', 'error');
                return;
            }
            
            // Level值越小权限越高，检查权限和审批需求
            if (requestedLevel < scopePermission.level) {
                // 检查是否是教务主任发布1级紧急通知
                if (currentUser.roleCode === 'ACADEMIC_ADMIN' && requestedLevel === 1) {
                    addLog('⚠️ 教务主任发布1级紧急通知，将进入审批流程', 'warning');
                    // 继续发布，但标记为需要审批
                    addLog('📋 注意：此通知将以"待审批"状态提交，需要校长审批', 'info');
                } else {
                    // 其他情况直接拒绝
                    const levelNames = {1: '紧急', 2: '重要', 3: '常规', 4: '提醒'};
                    showResult(`权限不足：您只能发布${scopePermission.level}-4级通知，无法发布${requestedLevel}级(${levelNames[requestedLevel]})通知`, 'error');
                    addLog(`❌ 权限验证失败: 请求级别=${requestedLevel}, 最高权限=${scopePermission.level}`, 'error');
                    return;
                }
            }
            
            const success = setOperationInProgress(true, 'publish');
            if (!success) {
                return; // 操作频率受限
            }
            
            try {
                showLoadingState('正在发布通知...');
                addLog('📤 开始发布通知', 'info');
                
                const cleanToken = currentToken.startsWith('Bearer ') ? currentToken.substring(7) : currentToken;
                
                // 构建发布请求
                // 检查是否需要审批
                const needsApproval = (currentUser.roleCode === 'ACADEMIC_ADMIN' && requestedLevel === 1);
                
                const publishData = {
                    title: title,
                    content: content,
                    level: parseInt(priority),  // ✅ 修复：后端期望level字段
                    targetScope: currentSelectedScope,
                    publisherName: currentUser.realName || currentUser.username,
                    publisherId: currentUser.id || currentUser.employeeId || 'unknown',
                    // 添加审批状态标识
                    status: needsApproval ? 2 : 3,  // 2=待审批, 3=已发布
                    requireApproval: needsApproval
                };
                
                addLog(`📋 发布数据: ${JSON.stringify(publishData, null, 2)}`, 'info');
                if (needsApproval) {
                    addLog('🔄 检测到审批需求，通知状态设置为：待审批(status=2)', 'warning');
                }
                
                const response = await fetchWithRetry(`${API_BASE}/admin-api/test/notification/api/publish-database`, {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${cleanToken}`,
                        'tenant-id': '1',
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(publishData)
                }, 1, 20000); // 发布请求只重试1次，但允许更长时间
                
                addLog(`📤 发布API请求: POST /admin-api/test/notification/api/publish-database`, 'info');
                addLog(`📥 发布API响应状态: ${response.status} ${response.statusText}`, 'info');
                
                if (response.ok) {
                    const result = await safeJsonParse(response);
                    addLog(`📥 发布API响应数据: ${JSON.stringify(result, null, 2)}`, 'info');
                    
                    if (result.code === 0) {
                        const notificationId = result.data?.notificationId || result.data?.id || 'N/A';
                        const scopeConfig = SCOPE_CONFIG[currentSelectedScope];
                        
                        if (needsApproval) {
                            // 需要审批的情况
                            addLog(`✅ 通知提交成功，进入审批流程！通知ID: ${notificationId}`, 'success');
                            
                            showResult(
                                '📋 通知已提交审批！',
                                'warning',
                                `
                                    <strong>通知ID：</strong>${notificationId}<br>
                                    <strong>发布范围：</strong>${scopeConfig?.icon} ${scopeConfig?.name}<br>
                                    <strong>优先级：</strong>🔴 Level ${priority} (紧急)<br>
                                    <strong>状态：</strong>⏳ 待审批<br>
                                    <strong>审批说明：</strong>1级紧急通知需要校长审批<br>
                                    <strong>提交时间：</strong>${new Date().toLocaleString()}
                                `
                            );
                        } else {
                            // 直接发布成功
                            addLog(`✅ 通知发布成功！通知ID: ${notificationId}`, 'success');
                            
                            showResult(
                                '🎉 通知发布成功！',
                                'success',
                                `
                                    <strong>通知ID：</strong>${notificationId}<br>
                                    <strong>发布范围：</strong>${scopeConfig?.icon} ${scopeConfig?.name}<br>
                                    <strong>优先级：</strong>Level ${priority}<br>
                                    <strong>发布时间：</strong>${new Date().toLocaleString()}
                                `
                            );
                        }
                        
                        // 清空表单
                        document.getElementById('publishForm').reset();
                        currentSelectedScope = null;
                        updateScopeOptions();
                        
                    } else {
                        throw new Error(result.message || '发布失败');
                    }
                } else {
                    let errorMessage = `HTTP ${response.status}`;
                    try {
                        const errorData = await safeJsonParse(response);
                        errorMessage += ` - ${errorData.message || errorData.msg || '未知错误'}`;
                    } catch {
                        const errorText = await response.text();
                        errorMessage += ` - ${errorText || '服务器错误'}`;
                    }
                    throw new Error(`发布请求失败: ${errorMessage}`);
                }
                
            } catch (error) {
                addLog(`❌ 发布失败: ${error.message}`, 'error');
                
                // 根据错误类型提供不同的用户反馈
                let userFriendlyMessage = '发布失败';
                if (error.message.includes('网络')) {
                    userFriendlyMessage = '网络连接异常，发布失败';
                } else if (error.message.includes('认证') || error.message.includes('Token')) {
                    userFriendlyMessage = '认证信息已过期，请重新登录';
                } else if (error.message.includes('权限')) {
                    userFriendlyMessage = '权限不足，无法发布此通知';
                } else if (error.message.includes('超时')) {
                    userFriendlyMessage = '请求超时，请稍后重试';
                } else {
                    userFriendlyMessage = `发布失败：${error.message}`;
                }
                
                showResult(userFriendlyMessage, 'error');
                
                // 如果是认证问题，自动清理状态
                if (error.message.includes('认证') || error.message.includes('401')) {
                    setTimeout(() => {
                        clearAuthStatus();
                        addLog('🔄 由于认证问题，已自动清理状态，请重新认证', 'info');
                    }, 2000);
                }
                
            } finally {
                hideLoadingState();
                setOperationInProgress(false);
            }
        }

        // ========================================
        // 辅助函数
        // ========================================
        
        // ========================================
        // 通知模板功能
        // ========================================

        function applyTemplate(templateType) {
            // 检查认证状态
            if (!currentUser) {
                showResult('请先认证登录后再应用模板', 'error');
                addLog('❌ 模板应用失败：用户未认证', 'error');
                return;
            }
            
            const template = NOTIFICATION_TEMPLATES[templateType];
            if (!template) {
                addLog(`❌ 未找到模板: ${templateType}`, 'error');
                return;
            }

            // 检查权限 - 如果用户没有模板推荐的范围权限，自动选择用户可用的范围
            let targetScope = template.scope;
            let scopeAdjusted = false;
            
            if (currentAvailableScopes.length > 0 && !currentAvailableScopes.includes(template.scope)) {
                // 智能选择范围：优先选择SCHOOL_WIDE > DEPARTMENT > CLASS > GRADE
                const scopePriority = ['SCHOOL_WIDE', 'DEPARTMENT', 'CLASS', 'GRADE'];
                targetScope = scopePriority.find(scope => currentAvailableScopes.includes(scope)) || currentAvailableScopes[0];
                scopeAdjusted = true;
                
                addLog(`⚠️ 模板默认范围 ${template.scope} 超出权限，自动调整为 ${targetScope}`, 'warning');
            }
            
            // 检查通知级别权限
            const permissions = ENHANCED_PERMISSION_MATRIX[currentUser.roleCode] || {};
            const scopePermission = permissions[targetScope];
            let levelAdjusted = false;
            let finalLevel = template.priority;
            
            if (scopePermission && template.priority < scopePermission.level) {
                // 检查是否是教务主任发布1级通知的特殊情况
                if (!(currentUser.roleCode === 'ACADEMIC_ADMIN' && template.priority === 1)) {
                    finalLevel = scopePermission.level;
                    levelAdjusted = true;
                    addLog(`⚠️ 模板默认级别 Level ${template.priority} 超出权限，调整为 Level ${finalLevel}`, 'warning');
                }
            }

            // 应用模板内容
            document.getElementById('notificationTitle').value = template.title;
            document.getElementById('notificationContent').value = template.content;
            document.getElementById('priorityLevel').value = finalLevel;
            
            // 设置发布范围
            if (currentAvailableScopes.includes(targetScope)) {
                selectScope(targetScope);
            }
            
            // 立即进行表单验证
            setTimeout(() => {
                validateFormField('notificationTitle', 'title');
                validateFormField('notificationContent', 'content');
            }, 100);

            // 用户反馈
            const templateNames = {
                emergency: '紧急通知',
                academic: '教务通知', 
                activity: '活动通知',
                meeting: '会议通知',
                maintenance: '维护通知',
                holiday: '假期通知'
            };

            // 构建反馈信息
            let feedbackMessage = `✅ 已应用${templateNames[templateType]}模板`;
            let adjustmentDetails = [];
            
            if (scopeAdjusted) {
                adjustmentDetails.push(`发布范围调整为: ${SCOPE_CONFIG[targetScope]?.name}`);
            }
            if (levelAdjusted) {
                const levelNames = {1: '紧急', 2: '重要', 3: '常规', 4: '提醒'};
                adjustmentDetails.push(`通知级别调整为: Level ${finalLevel} (${levelNames[finalLevel]})`);
            }
            
            if (adjustmentDetails.length > 0) {
                feedbackMessage += ` (权限调整: ${adjustmentDetails.join(', ')})`;
            }

            addLog(feedbackMessage, 'success');
            
            // 显示模板应用结果
            showResult(
                '📋 模板应用成功', 
                'success', 
                `<strong>模板类型：</strong>${templateNames[templateType]}<br>
                 <strong>发布范围：</strong>${SCOPE_CONFIG[targetScope]?.icon} ${SCOPE_CONFIG[targetScope]?.name}<br>
                 <strong>通知级别：</strong>Level ${finalLevel}<br>
                 ${adjustmentDetails.length > 0 ? '<br><strong>⚠️ 权限调整：</strong>' + adjustmentDetails.join('<br>• ') : ''}`,
                4000
            );
            
            // 高亮显示应用了模板
            const form = document.getElementById('publishForm');
            form.style.background = 'rgba(40, 167, 69, 0.1)';
            form.style.border = '2px solid rgba(40, 167, 69, 0.3)';
            
            setTimeout(() => {
                form.style.background = '';
                form.style.border = '';
            }, 3000);
        }

        function clearForm() {
            document.getElementById('publishForm').reset();
            currentSelectedScope = null;
            updateScopeOptions();
            addLog('🗑️ 表单已清空', 'info');
        }

        // ========================================
        // 工具函数
        // ========================================

        function getRoleMaxLevel(roleCode) {
            const permissions = ENHANCED_PERMISSION_MATRIX[roleCode] || {};
            const levels = Object.values(permissions).map(p => p.level);
            // Level值越小权限越高，所以取最小值表示最高权限级别
            return levels.length > 0 ? Math.min(...levels) : 0;
        }

        // ========================================
        // 事件监听器
        // ========================================
        
        document.addEventListener('DOMContentLoaded', function() {
            // 认证按钮事件
            document.getElementById('authBtn').addEventListener('click', authenticateUser);
            
            // 清除状态按钮事件
            document.getElementById('clearBtn').addEventListener('click', clearAuthStatus);
            
            // 表单提交事件
            document.getElementById('publishForm').addEventListener('submit', publishNotification);
            
            // 实时表单验证事件
            const titleField = document.getElementById('notificationTitle');
            const contentField = document.getElementById('notificationContent');
            const roleSelector = document.getElementById('roleSelector');
            
            // 标题实时验证
            titleField.addEventListener('blur', () => validateFormField('notificationTitle', 'title'));
            titleField.addEventListener('input', debounce(() => {
                if (titleField.value.trim()) {
                    validateFormField('notificationTitle', 'title');
                }
            }, 500));
            
            // 内容实时验证
            contentField.addEventListener('blur', () => validateFormField('notificationContent', 'content'));
            contentField.addEventListener('input', debounce(() => {
                if (contentField.value.trim()) {
                    validateFormField('notificationContent', 'content');
                }
            }, 800));
            
            // 角色选择器事件
            roleSelector.addEventListener('change', function() {
                if (this.value && currentUser && currentUser.roleCode !== this.value) {
                    validateRoleSwitch();
                }
            });
            
            // 初始化按钮状态
            setOperationInProgress(false);
            
            addLog('💪 系统增强功能已激活：', 'success');
            addLog('🔒 API超时重试、权限边界检查、操作频率保护', 'info');
            addLog('📱 响应式设计增强、表单实时验证、用户体验优化', 'info');
            addLog('🛡️ 重复操作防护、智能错误恢复、无障碍访问支持', 'info');
            addLog('💡 提示：请选择角色并认证后开始发布通知', 'info');
        });
        
        // 页面可见性检测 - 防止后台操作
        document.addEventListener('visibilitychange', function() {
            if (document.hidden && isOperationInProgress) {
                addLog('⚠️ 页面已切换到后台，当前操作可能受影响', 'warning');
            } else if (!document.hidden && isOperationInProgress) {
                addLog('👁️ 页面已回到前台，操作继续进行...', 'info');
            }
        });
        
        // 网络状态监测
        if ('navigator' in window && 'onLine' in navigator) {
            window.addEventListener('online', function() {
                addLog('🌐 网络连接已恢复', 'success');
                showResult('🌐 网络连接已恢复', 'success', '您可以继续进行操作', 3000);
            });
            
            window.addEventListener('offline', function() {
                addLog('⚠️ 网络连接已断开', 'warning');
                showResult('⚠️ 网络连接异常', 'warning', '请检查网络连接后重试操作', 5000);
            });
        }
        
        // 键盘快捷键支持
        document.addEventListener('keydown', function(e) {
            // Ctrl + Enter 快速发布
            if (e.ctrlKey && e.key === 'Enter' && currentUser && !isOperationInProgress) {
                const publishBtn = document.getElementById('publishBtn');
                if (!publishBtn.disabled) {
                    e.preventDefault();
                    addLog('⌨️ 快捷键发布：Ctrl+Enter', 'info');
                    publishBtn.click();
                }
            }
            
            // ESC 清除表单
            if (e.key === 'Escape' && !isOperationInProgress) {
                if (document.getElementById('publishForm').querySelector('input,textarea').value) {
                    e.preventDefault();
                    addLog('⌨️ 快捷键清空：ESC', 'info');
                    clearForm();
                }
            }
        });
        
        // 页面加载完成标记
        window.addEventListener('load', function() {
            addLog('✅ Phase 7.5 增强版页面完全加载完成', 'success');
        });
        
        // 防抖函数
        function debounce(func, wait) {
            let timeout;
            return function executedFunction(...args) {
                const later = () => {
                    clearTimeout(timeout);
                    func(...args);
                };
                clearTimeout(timeout);
                timeout = setTimeout(later, wait);
            };
        }
    </script>
</body>
</html>